package com.ruoyi.yipaiju.controller;

import com.google.common.collect.ImmutableMap;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.ApiResult;
import com.ruoyi.common.core.domain.entity.XcxUser;
import com.ruoyi.common.core.page.TableDataApi;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.yipaiju.domain.UserInvites;
import com.ruoyi.yipaiju.service.IUserInvitesService;
import com.ruoyi.yipaiju.service.IXcxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 小程序用户Controller
 * 
 * @author liuwp
 * @date 2023-03-01
 */
@RestController
@RequestMapping("/yipaiju/xcx_user")
public class XcxUserController extends BaseController
{
    @Autowired
    private IXcxUserService xcxUserService;
    @Autowired
    private IUserInvitesService userInvitesService;

    /**
     * 查询小程序用户列表
     */
    @PreAuthorize("@ss.hasPermi('yipaiju:xcx_user:list')")
    @GetMapping("/list")
    public TableDataInfo list(XcxUser xcxUser)
    {
        startPage();
        List<XcxUser> list = xcxUserService.selectXcxUserList1(xcxUser);
        return getDataTable(list);
    }

    /**
     * 导出小程序用户列表
     */
    @PreAuthorize("@ss.hasPermi('yipaiju:xcx_user:export')")
    @Log(title = "小程序用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, XcxUser xcxUser)
    {
        List<XcxUser> list = xcxUserService.selectXcxUserList(xcxUser);
        ExcelUtil<XcxUser> util = new ExcelUtil<XcxUser>(XcxUser.class);
        util.exportExcel(response, list, "小程序用户数据");
    }

    /**
     * 获取小程序用户详细信息
     */
    @PreAuthorize("@ss.hasPermi('yipaiju:xcx_user:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(xcxUserService.selectXcxUserById(id));
    }

    /**
     * 新增小程序用户
     */
    @PreAuthorize("@ss.hasPermi('yipaiju:xcx_user:add')")
    @Log(title = "小程序用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody XcxUser xcxUser)
    {
        return toAjax(xcxUserService.insertXcxUser(xcxUser));
    }

    /**
     * 修改小程序用户
     */
    @PreAuthorize("@ss.hasPermi('yipaiju:xcx_user:edit')")
    @Log(title = "小程序用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody XcxUser xcxUser)
    {
        return toAjax(xcxUserService.updateXcxUser(xcxUser));
    }

    /**
     * 删除小程序用户
     */
    @PreAuthorize("@ss.hasPermi('yipaiju:xcx_user:remove')")
    @Log(title = "小程序用户", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(xcxUserService.deleteXcxUserByIds(ids));
    }


    /**
     * 获取邀请列表
     * @param userId
     * @param depth 1：一级邀请，2：二级邀请
     * @return
     */
    @GetMapping("/{userId}/invites")
    public TableDataApi invitesList(@PathVariable("userId") Long userId, Integer depth)
    {
        List<UserInvites> userInvites = new ArrayList<>();
        if (depth == 1){
            startPageApi();
            userInvites = userInvitesService.selectUserInvitesList2(Builder.of(UserInvites::new)
                    .with(UserInvites::setInvitesId, userId)
                    .build());
        }else if (depth == 2){
            // 获取我邀请的一级  然后再查询二级
            List<UserInvites> userInvites1 = userInvitesService.selectUserInvitesList(Builder.of(UserInvites::new)
                    .with(UserInvites::setInvitesId, userId)
                    .build());
            if (userInvites1 != null && userInvites1.size() > 0){
                startPageApi();
                userInvites = userInvitesService.selectUserInvitesList2(Builder.of(UserInvites::new)
                        .with(UserInvites::setInviUser, "true")
                        .with(UserInvites::setInvitesIds, userInvites1.stream().map(item -> item.getUserId()).collect(Collectors.toList()))
                        .build());
            }
        }
        return getTableApi(userInvites);
    }


    /**
     * 用户邀请关系，返回一级邀请人和二级邀请人
     * @param userId
     * @return
     */
    @PostMapping("/invites/relation/{userId}")
    public ApiResult invitesRelation(@PathVariable("userId") Long userId){
        UserInvites userInvitesFirst = userInvitesService.selectOneUserInvites(Builder.of(UserInvites::new)
                .with(UserInvites::setUserId, userId)
                .build());
        UserInvites userInvitesSecond = null;
        if (userInvitesFirst != null){
            XcxUser xcxUser1 = xcxUserService.selectXcxUserById(userInvitesFirst.getInvitesId());
            if (xcxUser1 != null){
                userInvitesFirst.setNickname(xcxUser1.getNickname());
                userInvitesFirst.setAvatarUrl(xcxUser1.getAvatarUrl());
                userInvitesFirst.setPhone(xcxUser1.getPhone());
            }
            // 获取二级邀请
            userInvitesSecond = userInvitesService.selectOneUserInvites(Builder.of(UserInvites::new)
                    .with(UserInvites::setUserId, userInvitesFirst.getInvitesId())
                    .build());
            if (userInvitesSecond != null){
                XcxUser xcxUser2 = xcxUserService.selectXcxUserById(userInvitesSecond.getInvitesId());
                if (xcxUser2 != null){
                    userInvitesSecond.setNickname(xcxUser2.getNickname());
                    userInvitesSecond.setAvatarUrl(xcxUser2.getAvatarUrl());
                    userInvitesSecond.setPhone(xcxUser2.getPhone());
                }
            }
        }
        return ApiResult.success(ImmutableMap.of(
                "first", userInvitesFirst == null ? "" : userInvitesFirst,
                "second", userInvitesSecond == null ? "" : userInvitesSecond));
    }


}
